<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useHomeStore } from '@/stores/home'
import type { TimeRange } from '@/types/home'
import VChart from 'vue-echarts'
import * as echarts from 'echarts/core'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import { UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import {
  User,
  Calendar,
  Service,
  Check,
  Money,
  Warning
} from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import PetShowcase from '@/components/PetShowcase.vue'
import { storeToRefs } from 'pinia'

echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  BarChart,
  LineChart,
  PieChart,
  CanvasRenderer,
  UniversalTransition
])

const router = useRouter()
const homeStore = useHomeStore()
const authStore = useAuthStore()
const {
  recentMedical,
  recentAppointments,
  appointmentChartData
} = storeToRefs(homeStore)
const { fetchAppointmentChartData } = homeStore
const timeRange = ref<TimeRange>('month')

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': 'warning',
    'CONFIRMED': 'primary',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': '待确认',
    'CONFIRMED': '已确认',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return statusMap[status] || status
}

// 获取问候语
const greetingText = computed(() => {
  const hour = new Date().getHours()
  if (hour < 6) return '夜深了，请注意休息！'
  if (hour < 9) return '早上好，开始新的一天！'
  if (hour < 12) return '上午好，工作顺利！'
  if (hour < 14) return '中午好，请适当休息！'
  if (hour < 17) return '下午好，继续加油！'
  if (hour < 19) return '傍晚好，辛苦了！'
  return '晚上好，请注意休息！'
})

// 当前时间和日期
const currentTime = ref('')
const currentDate = ref('')
let timer: number

const updateDateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit',
    second: '2-digit'
  })
  currentDate.value = now.toLocaleDateString('zh-CN', { 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric',
    weekday: 'long'
  })
}

watch(timeRange, (val) => {
  fetchAppointmentChartData(val)
})

onMounted(() => {
  homeStore.fetchDashboardData()
  fetchAppointmentChartData(timeRange.value)
  updateDateTime()
  timer = window.setInterval(updateDateTime, 1000)
  
  // 添加调试信息
  console.log('HomeView mounted, recentAppointments:', recentAppointments.value)
  
  // 监听数据变化
  watch(recentAppointments, (newVal) => {
    console.log('recentAppointments changed:', newVal)
  }, { deep: true })
})

onUnmounted(() => {
  clearInterval(timer)
})

// 预约图表数据
const appointmentChartOption = computed(() => {
  const chartData = Array.isArray(appointmentChartData.value) ? appointmentChartData.value : []
  
  // 限制数据条数：本周最多7天，本月最多31天
  const maxDays = timeRange.value === 'week' ? 7 : 31
  const limitedData = chartData.slice(0, maxDays)
  
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: limitedData.map(item => item.date)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '预约数量',
        type: 'bar',
        data: limitedData.map(item => item.count),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#e6f3ff' },
            { offset: 0.5, color: '#b3d9ff' },
            { offset: 1, color: '#87ceeb' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#5f9ea0' },
              { offset: 0.7, color: '#87ceeb' },
              { offset: 1, color: '#e6f3ff' }
            ])
          }
        }
      }
    ]
  }
})

// 服务类型图表数据
const serviceChartOption = computed(() => ({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 10,
    data: homeStore.serviceTypeData.map(item => item.name)
  },
  series: [
    {
      name: '服务类型',
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 20,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: homeStore.serviceTypeData
    }
  ]
}))

const getIconForAction = (iconName: string) => {
  const iconMap: { [key: string]: any } = {
    'User': User,
    'Calendar': Calendar,
    'Service': Service,
    'Check': Check,
    'Money': Money,
    'Warning': Warning,
  }
  return iconMap[iconName] || Warning
}

// 定义一个所有可能的快捷操作的列表，将权限名称映射到具体的操作
const allPossibleActions = [
  { permission: '客户档案', title: '客户管理', icon: 'User', route: '/base/users' },
  { permission: '宠物档案', title: '宠物管理', icon: 'Service', route: '/base/pets' },
  { permission: '预约记录', title: '预约管理', icon: 'Calendar', route: '/base/appointments' },
  { permission: '疾病史', title: '医疗记录', icon: 'Check', route: '/medical-manage/medical' },
  { permission: '服务人员', title: '员工管理', icon: 'User', route: '/system/staffs' },
  { permission: '服务项目', title: '服务管理', icon: 'Service', route: '/system/services' },
  { permission: '疫苗接种记录', title: '疫苗接种', icon: 'Check', route: '/medical-manage/vaccine' },
  { permission: '驱虫记录', title: '驱虫记录', icon: 'Warning', route: '/medical-manage/dewormings' },
  { permission: '体检记录', title: '体检记录', icon: 'Check', route: '/medical-manage/checkups' },
  { permission: '服务资源', title: '资源管理', icon: 'Service', route: '/system/resources' },
];

// 用户角色的固定快捷操作
const userActions = [
  { title: '我的宠物', icon: 'Service', route: '/base/pets' },
  { title: '我的预约', icon: 'Calendar', route: '/base/appointments' },
  { title: '诊疗记录', icon: 'Check', route: '/medical-manage/medical' },
  { title: '疫苗记录', icon: 'Check', route: '/medical-manage/vaccine' },
];

const filteredQuickActions = computed(() => {
  const role = authStore.userRole;
  
  if (role === '用户') {
    return userActions;
  }

  const userPermissions = authStore.user?.permissions || [];

  // 对于管理员和员工，根据他们的实际权限动态生成快捷操作
  const availableActions = userPermissions
    .map(permission => allPossibleActions.find(action => action.permission === permission))
    .filter(action => action !== undefined); // 过滤掉没有对应快捷操作的权限

  return availableActions.slice(0, 4);
});

// 处理快捷操作点击
const handleQuickAction = (route: string) => {
  router.push(route)
}
</script>

<template>
  <div class="home-container">
    <!-- 欢迎信息 -->
    <div class="welcome-section">
      <div class="welcome-text">
        <h1>欢迎使用宠物之家管理系统</h1>
        <p>{{ greetingText }}</p>
      </div>
      <div class="welcome-time">
        <div class="time">{{ currentTime }}</div>
        <div class="date">{{ currentDate }}</div>
      </div>
      <div class="welcome-decoration"></div>
    </div>

    <!-- 宠物之星展示 -->
    <pet-showcase />

    <!-- 数据概览和快捷操作 -->
    <el-row :gutter="24" class="data-row">
      <!-- 图表区域 -->
      <el-col :span="16">
        <div class="charts-section">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <span class="chart-title">预约统计</span>
                <div class="time-range-selector">
                  <el-radio-group v-model="timeRange" size="small" class="custom-radio-group">
                    <el-radio-button label="week">本周</el-radio-button>
                    <el-radio-button label="month">本月</el-radio-button>
                  </el-radio-group>
                </div>
              </div>
            </template>
            <v-chart class="chart" :option="appointmentChartOption" autoresize />
          </el-card>
        </div>
      </el-col>

      <!-- 快捷操作 -->
      <el-col :span="8">
        <el-card class="action-card" shadow="hover">
          <template #header>
            <div class="action-header">
              <span class="section-title">快捷操作</span>
            </div>
          </template>
          <div class="action-list">
            <el-button
              v-for="action in filteredQuickActions"
              :key="action.title"
              class="action-button"
              @click="handleQuickAction(action.route)">
              <el-icon class="action-icon">
                <component :is="getIconForAction(action.icon)" />
              </el-icon>
              <div class="action-text">
                <span class="action-title">{{ action.title }}</span>
              </div>
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近医疗记录 -->
    <el-row class="data-row">
      <el-col :span="24">
        <el-card class="recent-card" shadow="hover">
          <template #header>
            <div class="recent-header">
              <span class="section-title">最近医疗记录</span>
              <el-button type="primary" size="small" plain @click="$router.push('/medical-manage/medical')">
                查看全部
              </el-button>
            </div>
          </template>
          <el-table :data="recentMedical" style="width: 100%" :show-header="true" size="small">
            <el-table-column prop="petName" label="宠物名称" width="100" />
            <el-table-column prop="diagnosisDate" label="诊断日期" width="120" />
            <el-table-column prop="medicalName" label="疾病名称" width="120" show-overflow-tooltip />
            <el-table-column prop="symptoms" label="症状描述" min-width="150" show-overflow-tooltip />
            <el-table-column prop="medicalResult" label="诊断结果" min-width="150" show-overflow-tooltip />
            <el-table-column prop="treatmentPlan" label="治疗方案" min-width="150" show-overflow-tooltip />
            <el-table-column prop="medication" label="用药记录" min-width="150" show-overflow-tooltip />
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 服务类型和最近预约 -->
    <el-row :gutter="24" class="data-row">
      <!-- 服务类型分布 -->
      <el-col :span="8">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="chart-header">
              <span class="chart-title">服务类型分布</span>
            </div>
          </template>
          <v-chart class="chart" :option="serviceChartOption" autoresize />
        </el-card>
      </el-col>

      <!-- 最近预约 -->
      <el-col :span="16">
        <el-card class="recent-card" shadow="hover">
          <template #header>
            <div class="recent-header">
              <span class="section-title">最近预约</span>
              <el-button type="primary" size="small" plain @click="$router.push('/base/appointments')">
                查看全部
              </el-button>
            </div>
          </template>
          <el-table :data="recentAppointments" style="width: 100%" :show-header="true" size="small">
            <el-table-column prop="appointmentId" label="预约编号" width="100" />
            <el-table-column prop="petId" label="宠物编号" width="100" />
            <el-table-column prop="serviceId" label="服务编号" width="100" />
            <el-table-column prop="startTime" label="开始时间" width="160" />
            <el-table-column prop="endTime" label="结束时间" width="160" />
            <el-table-column prop="appointmentStatus" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.appointmentStatus)" size="small">
                  {{ getStatusText(scope.row.appointmentStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="notes" label="备注" min-width="150" show-overflow-tooltip />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.home-container {
  padding: 12px 24px 24px 24px;
  min-height: 100%;
  background-color: #f7f3ed;
}

/* 欢迎区域 */
.welcome-section {
  position: relative;
  overflow: hidden;
  padding: 32px;
  margin-bottom: 24px;
  border-radius: 16px;
  color: #fff;
  background-size: 200% 200%;
  animation: gradientShift 15s ease infinite;
  background-image: linear-gradient(
    135deg,
    #36d1dc 0%,
    #5b86e5 50%,
    #8e54e9 100%
  );
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 1;
}

.welcome-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><circle cx="50" cy="50" r="40" fill="white" opacity="0.05"/></svg>');
  background-size: 150px;
  z-index: -1;
}

.welcome-decoration {
  position: absolute;
  top: -50px;
  right: -50px;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  z-index: -1;
}

.welcome-section:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.15);
}

.welcome-text h1 {
  margin: 0;
  font-size: 32px;
  font-weight: 700;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  letter-spacing: 1px;
}

.welcome-text p {
  margin: 12px 0 0;
  font-size: 18px;
  opacity: 0.9;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.welcome-time {
  text-align: right;
  position: relative;
  z-index: 1;
}

.welcome-time .time {
  font-size: 36px;
  font-weight: 700;
  font-family: 'Helvetica Neue', sans-serif;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.welcome-time .date {
  margin-top: 8px;
  font-size: 16px;
  opacity: 0.9;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

@keyframes gradientShift {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

/* 数据行 */
.data-row {
  margin-bottom: 24px;
}

/* 图表卡片 */
.chart-card {
  border-radius: 12px;
  height: 450px;
  border: none;
  transition: all 0.3s ease;
}

.chart-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
}

.chart {
  height: 320px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

/* 自定义选项按钮样式 */
.custom-radio-group {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 4px;
  border: 1px solid #e9ecef;
}

:deep(.custom-radio-group .el-radio-button__inner) {
  border: none;
  background: transparent;
  color: #6c757d;
  font-weight: 500;
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

:deep(.custom-radio-group .el-radio-button__inner:hover) {
  color: #409eff;
  background: rgba(64, 158, 255, 0.1);
}

:deep(.custom-radio-group .el-radio-button__original-radio:checked + .el-radio-button__inner) {
  background: linear-gradient(135deg, #409eff 0%, #36d1dc 100%);
  color: white;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  transform: translateY(-1px);
}

:deep(.custom-radio-group .el-radio-button__original-radio:checked + .el-radio-button__inner::before) {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0) 100%);
  border-radius: 6px;
}

:deep(.custom-radio-group .el-radio-button:first-child .el-radio-button__inner) {
  border-radius: 6px;
  border-left: none;
}

:deep(.custom-radio-group .el-radio-button:last-child .el-radio-button__inner) {
  border-radius: 6px;
  border-right: none;
}

:deep(.custom-radio-group .el-radio-button:not(:last-child) .el-radio-button__inner) {
  border-right: none;
}

:deep(.custom-radio-group .el-radio-button:not(:first-child) .el-radio-button__inner) {
  border-left: none;
}

/* 快捷操作 */
.action-card {
  border-radius: 12px;
  height: 450px;
  border: none;
  transition: all 0.3s ease;
}

.action-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
}

.action-header {
  margin-bottom: 16px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #313330;
}

.action-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 8px 0;
}

.action-button {
  height: 68px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
  padding: 0 16px;
  background-color: #fff;
  border: 1px solid #ebeef5;
  box-shadow: none;
  position: relative;
  overflow: hidden;
}

.action-button:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.action-button:active {
  transform: translateY(1px);
}

.action-icon {
  font-size: 20px;
  color: #409eff;
  background-color: #ecf5ff;
  padding: 10px;
  border-radius: 6px;
  margin-right: 16px;
  flex-shrink: 0;
}

.action-text {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  flex-grow: 1;
  overflow: hidden;
}

.action-title {
  font-size: 15px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 2px;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.action-desc {
  font-size: 12px;
  color: #909399;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.action-button::after {
  content: '';
  position: absolute;
  top: 0;
  right: 16px;
  height: 100%;
  display: flex;
  align-items: center;
  color: #c0c4cc;
  font-family: 'element-icons';
  content: '\e6e0';
  font-size: 16px;
  transition: all 0.3s ease;
  opacity: 0;
}

.action-button:hover::after {
  opacity: 1;
  transform: translateX(5px);
}

/* 最近数据卡片 */
.recent-card {
  border-radius: 12px;
  border: none;
  transition: all 0.3s ease;
}

.recent-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
}

.recent-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

@media (max-width: 992px) {
  .data-row .el-col {
    width: 100%;
    margin-bottom: 24px;
  }
  
  .chart-card, .action-card {
    height: auto;
  }
  
  .chart {
    height: 250px;
  }
}

@media (max-width: 768px) {
  .welcome-section {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .welcome-time {
    margin-top: 16px;
    text-align: left;
  }
}
</style>
